<template>
  <a-drawer
    title="分组排序"
    :visible="visible"
    :width="600"
    :body-style="{
      paddingBottom: '60px',
      height: 'calc(100% - 55px)',
    }"
    @close="onClose"
  >
    <section class="beauty-scroller-bar">
      <a-alert message="拖动分组名称进行排序" />
      <draggable v-model="catList" group="cat" item-key="id">
        <template #item="{ element }">
          <div class="cat-name">{{ element.cat_name }}</div>
        </template>
      </draggable>
    </section>
    <div class="drawer-footer">
      <a-space>
        <a-button @click.prevent="onClose">取消</a-button>
        <a-button type="primary" @click.prevent="onSubmit"> 保存 </a-button>
      </a-space>
    </div>
  </a-drawer>
</template>

<script>
import { defineComponent, watch, computed, reactive, toRefs } from "vue";
import { Form, message } from "ant-design-vue";
import draggable from "vuedraggable";
import request from "../../../../common/utils/request";

export default defineComponent({
  name: "CatSort",
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    list: {
      type: Array,
      default: () => [],
    },
  },
  components: { draggable },
  setup(props, { emit }) {
    const state = reactive({
      catList: [],
    });

    const onSubmit = () => {
      request
        .put("/work_approval", "/manage/category/sort", {
          sort_arr: state.catList.map((item, index) => ({
            id: item.id,
            sort: state.catList.length - index,
          })),
          needMsg: true,
        })
        .then((res) => {
          message.success(res.msg || "操作成功！");
          emit("success");
        });
    };

    const onClose = () => {
      emit("cancel");
    };

    watch(
      () => props.visible,
      (val) => {
        if (val) {
          state.catList = props.list;
        }
      }
    );
    return {
      ...toRefs(state),
      onClose,
      onSubmit,
    };
  },
});
</script>

<style scoped>
.beauty-scroller-bar {
  height: 100%;
  overflow: hidden auto;
}
.cat-name {
  padding: 0 20px;
  border: 1px solid #f1f1f1;
  line-height: 40px;
  margin-top: 10px;
  cursor: all-scroll;
  border-radius: 8px;
}
</style>
